import * as crypto from 'crypto';
import * as _ from "lodash";
import { ObjectId } from 'mongodb';
import { isValidObjectId } from 'mongoose';
import { KWError } from "../common/error";
import { KWCode } from "../common/code";

export const md5 = (content: string): string => {
  return crypto.createHash('md5').update(content).digest('hex');
}

export const parseId = (id?: string | ObjectId): ObjectId => {
  if (id) {
    if(isValidObjectId(id)) {
      return new ObjectId(id);
    } else {
      throw new KWError(KWCode.invalidInput, `id is invalid: ${id}`)
    }
  } else {
    return new ObjectId();
  }
}

export const camelToUnderline = <T extends Object, U extends Object>(data: T): U => {
  const keys = Object.keys(data);
  const obj: U = Object.create({});
  keys.forEach(camelKey => {
    let rawKey = camelKey;
    // 如果以 _s 或 _i 开头， 去掉头部
    if (camelKey.startsWith('_s') || camelKey.startsWith('_i')) {
      rawKey = camelKey.slice(2);
    }
    const underlineKey = rawKey.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/, "");
    if (_.isArray(data[camelKey]) && _.isPlainObject(data[camelKey][0])) {
      obj[underlineKey] = data[camelKey].map((dt: object) => { return camelToUnderline(dt); });
    } else if (_.isPlainObject(data[camelKey])) {
      obj[underlineKey] = camelToUnderline(data[camelKey]);
    } else {
      obj[underlineKey] = data[camelKey];
    }
  })
  return obj;
}
